#!/usr/bin/env python2.5
# encoding: utf-8
"""
SQLStream.py

Created by Alakazam on 2007-07-05.
Copyright (c) 2007 . All rights reserved.
"""

from abstract import abstract
from Stream import Stream

class SQLStream(Stream):
  def __init__(self, DBServer, name):
    if type(self) is SQLStream: abstract()
    
    self.name     = name
    self.DBServer = DBServer
  
  def __repr__(self):
    try:
      name = self.name
    except AttributeError:
      name = "Undefined"
    
    return "SQLStream('%s', '%s')"%(
      self.DBServer, name)
  
  def get(self, timestamp):
    return self.DBServer.execute(
      "SELECT value FROM " + self.name + " WHERE startTime <= ? AND endTime >= ?",
      (timestamp, timestamp))
  
  def getIter(self, startTime, endTime):
    return self.DBServer.execute(
      " SELECT id, startTime, endTime, value \
          FROM `" + self.name + "` \
         WHERE (startTime >= ? OR endTime >= ?) \
           AND (startTime <= ? OR endTime <= ?) \
      ORDER BY startTime, endTime, value",
      (startTime, startTime, endTime, endTime))
  
  def getById(self, id):
    return self.DBServer.execute(
      "SELECT id, startTime, endTime, value FROM `" + self.name + "` WHERE id = ?",
      (id,)).fetchone()
  
  def getNextStart(self, startTime):
    return self.DBServer.execute(
      "SELECT MIN(startTime) FROM `" + self.name + "` WHERE startTime >= ?",
      (startTime,)
        ).fetchone()[0]
  
  def getNextEnd(self, endTime):
    return self.DBServer.execute(
      "SELECT MIN(endTime) FROM `" + self.name + "` WHERE endTime >= ?",
      (endTime,)
        ).fetchone()[0]
  
  def getPreviousStart(self, startTime):
    return self.DBServer.execute(
      "SELECT MAX(startTime) FROM `" + self.name + "` WHERE startTime <= ?",
      (startTime,)
        ).fetchone()[0]
  
  def getPreviousEnd(self, endTime):
    return self.DBServer.execute(
      "SELECT MAX(endTime) FROM `" + self.name + "` WHERE endTime <= ?",
      (endTime,)
        ).fetchone()[0]
  
  def getFirstStart(self):
    return self.DBServer.execute(
      "SELECT MIN(startTime) FROM `" + self.name + "`"
        ).fetchone()[0]
  
  def getLastEnd(self):
    return self.DBServer.execute(
      "SELECT MAX(endTime) FROM `" + self.name + "`"
        ).fetchone()[0]
  
  def getMinEventLength(self):
    return self.DBServer.execute(
      "SELECT MIN(endTime - startTime) FROM `" + self.name + "`"
        ).fetchone()[0]
  
  def getMaximumValue(self):
    return self.DBServer.execute(
      "SELECT MAX(value) FROM `" + self.name + "`"
        ).fetchone()[0]
  
  def getMinimumValue(self):
    return self.DBServer.execute(
      "SELECT MIN(value) FROM `" + self.name + "`"
        ).fetchone()[0]
  
